var nextGreaterElement = function(nums1, nums2) {
  let len1 = nums1.length, len2 = nums2.length;
  const map = new Map();
  const stack = [];

  for (let i = len2 - 1; i >= 0; i--) {
    let num = nums2[i];
    while (stack.length && num >= stack[stack.length - 1]) {
      stack.pop();
    }
    if (stack.length) {
      map.set(num, stack[stack.length - 1]);
    } else {
      map.set(num, -1);
    }
    stack.push(num);
  }

  let ans = [];

  for (let i = 0; i < len1; i++) {
    ans[i] = map.get(nums1[i]);
  }

  return ans;
};

const nums1 = [4,1,2], nums2 = [1,3,4,2];
console.log(nextGreaterElement(nums1, nums2)); // [3,-1,4,-1]